﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.Common.Utility.EnumToos;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;
using NPOI.HSSF.UserModel;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class OrdersController : BaseController
    {
        private readonly OrderExtBll _orderExtBll = new OrderExtBll();

        public ActionResult List(int orderStatus = (int) CommonEnum.OrderStatus.NewOrder)
        {
            var userAgent = Request.UserAgent;
            var isWeiXin = !string.IsNullOrEmpty(userAgent) && userAgent.ToLower().Contains("micromessenger");
            ViewBag.OrderStatus = orderStatus;
            if (CurrentUser.RoleId == (int) CommonEnum.McAccountRole.Boss)//老板
            {
                return View(isWeiXin ? "BossPhoneList" : "BossPcList", CurrentUser);
            }
            //店员
            var shop = ShopsBLL.Instance.GetModel(CurrentUser.ShopId);
            if (shop == null)
            {
                return RedirectToAction("Update", "McAccounts");
            }
            ViewBag.IsOpenOrderGrab = shop.IsOpenOrderGrab;
            if (!shop.IsOpenOrderGrab && orderStatus == (int)CommonEnum.OrderStatus.NewOrder)
            {
                ViewBag.OrderStatus = (int) CommonEnum.OrderStatus.BeingDelivered;
            }
            return View(isWeiXin ? "DeliveryPhoneList" : "DeliveryPcList", CurrentUser);
        }

        [HttpPost]
        public JsonResult Listing(int draw, int start, int length, string keyWords, string orderNo, string startTime, string endTime, int orderStatus = 1)
        {
            try
            {
                var result = new TableDataViewDto<ViewOrdersDto>
                {
                    data = new List<ViewOrdersDto>(),
                    draw = draw,
                    recordsFiltered = 0,
                    recordsTotal = 0
                };
                var pageIndex = (start / length) + 1;
                var deliveryAccountId = 0;
                if (CurrentUser.RoleId == (int)CommonEnum.McAccountRole.Delivery)
                {
                    var shop = ShopsBLL.Instance.GetModel(CurrentUser.ShopId);
                    if (shop == null)
                    {
                        return Json(result);
                    }
                    if (orderStatus == (int)CommonEnum.OrderStatus.NewOrder)
                    {
                        if (!shop.IsOpenOrderGrab)
                        {
                            deliveryAccountId = CurrentUser.AccountId;
                            orderStatus = (int) CommonEnum.OrderStatus.BeingDelivered;
                        }
                    }
                    else
                    {
                        deliveryAccountId = CurrentUser.AccountId;
                    }
                }
                var orderData = "Id desc ";
                if (orderStatus == (int) CommonEnum.OrderStatus.ToBePaid ||
                    orderStatus == (int)CommonEnum.OrderStatus.NewOrder ||
                    orderStatus == (int)CommonEnum.OrderStatus.BeingDelivered)
                {
                    orderData = "Id asc ";
                }
                var theList = OrdersBLL.Instance.GetPagingList(new List<MagModules>(),draw, pageIndex, length, keyWords, orderNo, startTime, endTime, CurrentUser.ShopId.ToString(), orderStatus, deliveryAccountId, orderData, true, true, CurrentUser.RoleId == (int)CommonEnum.McAccountRole.Delivery);
                return Json(theList);
            }
            catch { }
            return Json(null);
        }

        public ActionResult Detail(int id)
        {
            var orderModel = OrdersBLL.Instance.GetModel(id);
            var viewOrder = new ViewOrdersDto();
            if (orderModel != null && orderModel.ShopId == CurrentUser.ShopId)
            {
                viewOrder.Id = orderModel.Id;
                viewOrder.OrderNo = orderModel.OrderNo;
                viewOrder.OrderTime = orderModel.OrderTime.ToString();
                viewOrder.OrderStatus = ((CommonEnum.OrderStatus) orderModel.OrderStatus).GetDescription();
                viewOrder.ShopId = orderModel.ShopId;
                viewOrder.ShopCustomerNumber = orderModel.ShopCustomerNumber;
                viewOrder.OldOrderPhone = orderModel.OldOrderPhone;
                viewOrder.CommodityQuantity = orderModel.CommodityQuantity;
                viewOrder.PayPrice = orderModel.PayPrice.ToString();
                viewOrder.DiscountPrice = orderModel.DiscountPrice.ToString();
                viewOrder.NormalPrice = orderModel.NormalPrice.ToString();
                viewOrder.RandomPayDiscount = orderModel.RandomPayDiscount;
                viewOrder.CouponValue = orderModel.CouponValue;

                viewOrder.CouponResume = OrdersBLL.Instance.GetOrderCouponUseResume(orderModel.Id).Replace("<br/>", "\r\n"); ;

                viewOrder.PayWay = ((CommonEnum.OrderPayWay) orderModel.PayWay).GetDescription();
                if (orderModel.PayPrice == 0 && !string.IsNullOrWhiteSpace(viewOrder.CouponResume))
                {
                    viewOrder.PayWay = "电子水票（券）支付";
                }

                viewOrder.ReceiverName = orderModel.ReceiverName;
                viewOrder.ReceiverPhone = orderModel.ReceiverPhone;
                viewOrder.ReceiverAddress = orderModel.ReceiverAddress;
                viewOrder.Remark = orderModel.Remark;
                viewOrder.SysRemark = orderModel.SysRemark;
                if (orderModel.AssignerAccountId > 0)
                {
                    viewOrder.AssignTime = orderModel.AssignTime != null ? orderModel.AssignTime.ToString() : null;
                }
                if (orderModel.DeliveryAccountId > 0)
                {
                    var deliveryAccount = McAccountsBLL.Instance.GetModel(orderModel.DeliveryAccountId);
                    if (deliveryAccount != null)
                    {
                        viewOrder.DeliveryDisplayName = deliveryAccount.DisplayName;
                        viewOrder.DeliveryMobile = deliveryAccount.Mobile;
                    }
                    viewOrder.DeliveryTime = orderModel.DeliveryTime != null ? orderModel.DeliveryTime.ToString() : null;
                }
                viewOrder.ReceivingTime = orderModel.ReceivingTime != null ? orderModel.ReceivingTime.ToString() : null;
                viewOrder.FinishTime = orderModel.FinishTime != null ? orderModel.FinishTime.ToString() : null;
                viewOrder.CancelTime = orderModel.CancelTime != null ? orderModel.CancelTime.ToString() : null;
                viewOrder.RejectTime = orderModel.RejectTime != null ? orderModel.RejectTime.ToString() : null;
                viewOrder.RemindTime = orderModel.RemindTime != null ? orderModel.RemindTime.ToString() : null;
                viewOrder.ConsumerSendTime = orderModel.ConsumerSendTime;
                viewOrder.OrderDetailList = OrderDetailBLL.Instance.GetModelList("OrderId=" + orderModel.Id);
                var action = "";
                switch (orderModel.OrderStatus)
                {
                    case (int)CommonEnum.OrderStatus.NewOrder: //等待派单
                        //老板可派单
                        action += "<a data-target='#assignModal' data-toggle='modal' class='btn btn-info' onclick=assign(" + orderModel.Id + ");>派单</a> ";
                        break;
                    case (int)CommonEnum.OrderStatus.BeingDelivered: //正在配送
                        //老板可点击已送达
                        action += "<a class='btn btn-success' onclick=arrived(" + orderModel.Id + ");>已送达</a> ";
                        break;
                    case (int)CommonEnum.OrderStatus.Arrived: //已送到
                        //老板可点击订单完成
                        action += "<a class='btn btn-success' onclick=complete(" + orderModel.Id + ");>订单完成</a> ";
                        break;
                }
                if (orderModel.PayWay != (int)CommonEnum.OrderPayWay.WeChat)
                {
                    if (orderModel.OrderStatus != (int)CommonEnum.OrderStatus.Finished &&
                        orderModel.OrderStatus != (int)CommonEnum.OrderStatus.Canceled &&
                        orderModel.OrderStatus != (int)CommonEnum.OrderStatus.Rejected)
                    {
                        //非在线支付可取消
                        action += "<a data-target='#cancelOrRejectedModal' data-toggle='modal' class='btn btn-danger' onclick=cancel(" + orderModel.Id + ");>取消</a> ";
                    }
                    if (orderModel.OrderStatus == (int)CommonEnum.OrderStatus.BeingDelivered ||
                        orderModel.OrderStatus == (int)CommonEnum.OrderStatus.Arrived)
                    {
                        //店铺老板可退回
                        action += "<a data-target='#cancelOrRejectedModal' data-toggle='modal' class='btn btn-danger' onclick=back(" + orderModel.Id + ");>退回</a> ";
                    }
                }
                var consumerModel = ConsumerBLL.Instance.GetModel(orderModel.ConsumerId);
                if (consumerModel != null)
                {
                    ViewBag.NickName = consumerModel.NickName + "（客户编号：" + consumerModel.Id + "）";
                }
                ViewBag.Action = action;
            }
            return View(viewOrder);
        }

        /// <summary>
        /// 【老板】订单分派
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <param name="deliveryId">配送人员Id</param>
        /// <remarks>2016-09-14 lk update 订单状态为2的情况下可重复派单</remarks>
        [HttpPost]
        public JsonResult Assign(int orderId, int deliveryId)
        {
            var result = new Result();
            var oldOrder = OrdersBLL.Instance.GetModel(orderId);
            if (oldOrder != null && oldOrder.ShopId == CurrentUser.ShopId && CurrentUser.RoleId == (int) CommonEnum.McAccountRole.Boss)
            {
                var newOrder = oldOrder.CloneExt<Orders>();
                if (newOrder.OrderStatus > (int)CommonEnum.OrderStatus.BeingDelivered)
                {
                    result.Message = "订单状态已更新，请刷新页面";
                    return Json(result);
                }
                var delivery = McAccountsBLL.Instance.GetModel(deliveryId);
                if (delivery != null && delivery.ShopId == CurrentUser.ShopId)
                {
                    newOrder.AssignerAccountId = CurrentUser.AccountId;
                    newOrder.DeliveryAccountId = deliveryId;
                    newOrder.OrderStatus = (int)CommonEnum.OrderStatus.BeingDelivered;
                    var orderTracking = new OrderTracking
                    {
                        OrderId = orderId,
                        OptDesc = _orderExtBll.GetOrderTackingOptDesc(newOrder.OrderStatus, newOrder),
                        OptTime = DateTime.Now,
                        OrderStatus = newOrder.OrderStatus,
                        PreOrderStatus = oldOrder.OrderStatus,
                        OptAccountId = CurrentUser.AccountId,
                        IpAddress = IpHelper.IPAddress,
                        IsAccountAdmin = true
                    };
                    result.Status = _orderExtBll.UpdateMainOrderInfo(newOrder, oldOrder, orderTracking).Status;
                    if (result.Status)
                    {
                        result.Message = "订单已成功分派给“" + delivery.DisplayName + "”";
                    }
                    //派单后推送给店员模板消息
                    _orderExtBll.SendNewOrderWxTemplateMsg(newOrder, true, deliveryId);
                    //发送消息到商家后台
                    _orderExtBll.SendMsgToMcManageWeb(newOrder.ShopId, newOrder.OrderNo,
                        newOrder.ConsumerName, CommonEnum.PushingMsgType.NewOrder, deliveryId.ToString());
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请刷新重试";
            }
            return Json(result);
        }

        /// <summary>
        /// 【老板、店员】订单送达
        /// </summary>
        [HttpPost]
        public JsonResult Arrived(int orderId)
        {
            var result = new Result();
            var oldOrder = OrdersBLL.Instance.GetModel(orderId);
            if (oldOrder != null && oldOrder.ShopId == CurrentUser.ShopId)
            {
                if (oldOrder.OrderStatus != (int)CommonEnum.OrderStatus.BeingDelivered)
                {
                    result.Message = "订单状态已更改，请刷新";
                    return Json(result);
                }
                var newOrder = oldOrder.CloneExt<Orders>();
                newOrder.OrderStatus = (int)CommonEnum.OrderStatus.Arrived;
                var orderTracking = new OrderTracking
                {
                    OrderId = orderId,
                    OptDesc = _orderExtBll.GetOrderTackingOptDesc(newOrder.OrderStatus, newOrder),
                    OptTime = DateTime.Now,
                    OrderStatus = newOrder.OrderStatus,
                    PreOrderStatus = oldOrder.OrderStatus,
                    OptAccountId = CurrentUser.AccountId,
                    IpAddress = IpHelper.IPAddress,
                    IsAccountAdmin = true
                };
                result.Status = _orderExtBll.UpdateMainOrderInfo(newOrder, oldOrder, orderTracking).Status;
                if (result.Status)
                {
                    result.Message = "操作成功，商品已送达";
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请刷新重试";
            }
            return Json(result);
        }

        /// <summary>
        /// 【老板、店员】订单完成
        /// </summary>
        [HttpPost]
        public JsonResult Complete(int orderId)
        {
            var result = new Result();
            var oldOrder = OrdersBLL.Instance.GetModel(orderId);
            if (oldOrder != null && oldOrder.ShopId == CurrentUser.ShopId)
            {
                if (oldOrder.OrderStatus != (int)CommonEnum.OrderStatus.Arrived)
                {
                    result.Message = "订单状态已更改，请刷新";
                    return Json(result);
                }
                var newOrder = oldOrder.CloneExt<Orders>();
                newOrder.OrderStatus = (int)CommonEnum.OrderStatus.Finished;
                var orderTracking = new OrderTracking
                {
                    OrderId = orderId,
                    OptDesc = _orderExtBll.GetOrderTackingOptDesc(newOrder.OrderStatus, newOrder),
                    OptTime = DateTime.Now,
                    OrderStatus = newOrder.OrderStatus,
                    PreOrderStatus = oldOrder.OrderStatus,
                    OptAccountId = CurrentUser.AccountId,
                    IpAddress = IpHelper.IPAddress,
                    IsAccountAdmin = true
                };
                result.Status = _orderExtBll.UpdateMainOrderInfo(newOrder, oldOrder, orderTracking).Status;
                if (result.Status)
                {
                    result.Message = "操作成功，订单已完成";
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请刷新重试";
            }
            return Json(result);
        }

        /// <summary>
        /// 【老板】订单取消
        /// </summary>
        [HttpPost]
        public JsonResult Cancel(int orderId, string sysRemark)
        {
            var result = new Result();
            var oldOrder = OrdersBLL.Instance.GetModel(orderId);
            if (oldOrder != null && oldOrder.ShopId == CurrentUser.ShopId && CurrentUser.RoleId == (int)CommonEnum.McAccountRole.Boss)
            {
                if (oldOrder.PayWay == (int) CommonEnum.OrderPayWay.WeChat)
                {
                    result.Message = "在线支付订单不可取消";
                    return Json(result);
                }
                if (oldOrder.OrderStatus == (int) CommonEnum.OrderStatus.Finished ||
                    oldOrder.OrderStatus == (int) CommonEnum.OrderStatus.Canceled ||
                    oldOrder.OrderStatus == (int) CommonEnum.OrderStatus.Rejected)
                {
                    result.Message = "订单当前状态不可操作";
                    return Json(result);
                }
                var newOrder = oldOrder.CloneExt<Orders>();
                newOrder.OrderStatus = (int)CommonEnum.OrderStatus.Canceled;
                newOrder.SysRemark = sysRemark;
                var orderTracking = new OrderTracking
                {
                    OrderId = orderId,
                    OptDesc = _orderExtBll.GetOrderTackingOptDesc(newOrder.OrderStatus, newOrder),
                    OptTime = DateTime.Now,
                    OrderStatus = newOrder.OrderStatus,
                    PreOrderStatus = oldOrder.OrderStatus,
                    OptAccountId = CurrentUser.AccountId,
                    IpAddress = IpHelper.IPAddress,
                    IsAccountAdmin = true
                };
                result.Status = _orderExtBll.UpdateMainOrderInfo(newOrder, oldOrder, orderTracking).Status;
                if (result.Status)
                {
                    result.Message = "操作成功，订单已取消";
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请刷新重试";
            }
            return Json(result);
        }

        /// <summary>
        /// 【老板】订单退回
        /// </summary>
        [HttpPost]
        public JsonResult Back(int orderId, string sysRemark)
        {
            var result = new Result();
            var oldOrder = OrdersBLL.Instance.GetModel(orderId);
            if (oldOrder != null && oldOrder.ShopId == CurrentUser.ShopId && CurrentUser.RoleId == (int)CommonEnum.McAccountRole.Boss)
            {
                if (oldOrder.PayWay == (int)CommonEnum.OrderPayWay.WeChat)
                {
                    result.Message = "在线支付订单不可退回";
                    return Json(result);
                }
                if (oldOrder.OrderStatus != (int)CommonEnum.OrderStatus.BeingDelivered &&
                    oldOrder.OrderStatus != (int)CommonEnum.OrderStatus.Arrived)
                {
                    result.Message = "订单当前状态不可操作";
                    return Json(result);
                }
                var newOrder = oldOrder.CloneExt<Orders>();
                newOrder.OrderStatus = (int)CommonEnum.OrderStatus.Rejected;
                newOrder.SysRemark = sysRemark;
                var orderTracking = new OrderTracking
                {
                    OrderId = orderId,
                    OptDesc = _orderExtBll.GetOrderTackingOptDesc(newOrder.OrderStatus, newOrder),
                    OptTime = DateTime.Now,
                    OrderStatus = newOrder.OrderStatus,
                    PreOrderStatus = oldOrder.OrderStatus,
                    OptAccountId = CurrentUser.AccountId,
                    IpAddress = IpHelper.IPAddress,
                    IsAccountAdmin = true
                };
                result.Status = _orderExtBll.UpdateMainOrderInfo(newOrder, oldOrder, orderTracking).Status;
                if (result.Status)
                {
                    result.Message = "操作成功，订单已退回";
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请刷新重试";
            }
            return Json(result);
        }

        /// <summary>
        /// 【店员】抢单
        /// </summary>
        [HttpPost]
        public JsonResult Grab(int orderId)
        {
            var result = new Result();
            var oldOrder = OrdersBLL.Instance.GetModel(orderId);
            if (oldOrder != null && oldOrder.ShopId == CurrentUser.ShopId)
            {
                var shopModel = ShopsBLL.Instance.GetModel(oldOrder.ShopId);
                if (shopModel == null || !shopModel.IsOpenOrderGrab)
                {
                    result.Message = "您的店铺未开启抢单模式";
                    return Json(result);
                }
                if (oldOrder.OrderStatus != (int)CommonEnum.OrderStatus.NewOrder)
                {
                    if (oldOrder.OrderStatus == (int)CommonEnum.OrderStatus.BeingDelivered)
                    {
                        result.Message = "抱歉，订单已被他人抢去";
                    }
                    else
                    {
                        result.Message = "订单状态已更改，请刷新";
                    }
                    return Json(result);
                }
                var newOrder = oldOrder.CloneExt<Orders>();
                newOrder.AssignerAccountId = CurrentUser.AccountId;
                newOrder.DeliveryAccountId = CurrentUser.AccountId;
                newOrder.OrderStatus = (int)CommonEnum.OrderStatus.BeingDelivered;
                var orderTracking = new OrderTracking
                {
                    OrderId = orderId,
                    OptDesc = _orderExtBll.GetOrderTackingOptDesc(newOrder.OrderStatus, newOrder),
                    OptTime = DateTime.Now,
                    OrderStatus = newOrder.OrderStatus,
                    PreOrderStatus = oldOrder.OrderStatus,
                    OptAccountId = CurrentUser.AccountId,
                    IpAddress = IpHelper.IPAddress,
                    IsAccountAdmin = false
                };
                result.Status = _orderExtBll.UpdateMainOrderInfo(newOrder, oldOrder, orderTracking).Status;
                if (result.Status)
                {
                    result.Message = "抢单成功";
                }
            }
            if (result.Status == false && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请刷新重试";
            }
            return Json(result);
        }

        /// <summary>
        /// 所有订单数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetCount()
        {
            int shopId = CurrentUser.ShopId;
            var count = OrdersBLL.Instance.GetOneShopAllOrders(shopId).Count;
            return Json(count);
        }

        /// <summary>
        /// 导出订单
        /// </summary>
        /// <remarks>2016-09-28 万乐园 创建</remarks>
        [HttpPost]
        public JsonResult ExportOrders(string keyWords, string orderNo, string startTime, string endTime, int orderStatus = -1)
        {
            var result = new Result();
            try
            {
                var orderList = OrdersBLL.Instance.GetExportOrderList(keyWords, orderNo, startTime, endTime, CurrentUser.ShopId.ToString(), orderStatus);

                #region 生成excel文件
                var book = new HSSFWorkbook();
                var sheet = book.CreateSheet("订单数据");
                var titleRow = sheet.CreateRow(0);

                #region 表头
                titleRow.CreateCell(0).SetCellValue("销售日期");
                titleRow.CreateCell(1).SetCellValue("订单时间");
                titleRow.CreateCell(2).SetCellValue("订单号");
                titleRow.CreateCell(3).SetCellValue("支付流水号");
                titleRow.CreateCell(4).SetCellValue("条形码");
                titleRow.CreateCell(5).SetCellValue("购买产品");
                titleRow.CreateCell(6).SetCellValue("购买数量");
                titleRow.CreateCell(7).SetCellValue("产品单价");
                titleRow.CreateCell(8).SetCellValue("支付金额");
                titleRow.CreateCell(9).SetCellValue("优惠金额");
                titleRow.CreateCell(10).SetCellValue("支付方式");
                titleRow.CreateCell(11).SetCellValue("客户地址");
                titleRow.CreateCell(12).SetCellValue("客户姓名");
                titleRow.CreateCell(13).SetCellValue("客户电话");
                titleRow.CreateCell(14).SetCellValue("订单备注");
                titleRow.CreateCell(15).SetCellValue("订单状态");
                titleRow.CreateCell(16).SetCellValue("配送店铺电话");
                titleRow.CreateCell(17).SetCellValue("所属门店");
                titleRow.CreateCell(18).SetCellValue("门店账号");
                titleRow.CreateCell(19).SetCellValue("转移门店");
                titleRow.CreateCell(20).SetCellValue("转移门店账号");
                titleRow.CreateCell(21).SetCellValue("备注1");
                titleRow.CreateCell(22).SetCellValue("订单票券详情");
                #endregion

                var rowIndex = 1;
                for (var i = 0; i < orderList.Count; i++)
                {
                    var dataRow = sheet.CreateRow(rowIndex);
                    dataRow.CreateCell(0).SetCellValue(orderList[i].OrderTime.ToString());//销售日期
                    dataRow.CreateCell(1).SetCellValue(orderList[i].OrderTime.ToString());//订单日期
                    dataRow.CreateCell(2).SetCellValue(orderList[i].OrderNo);//订单号
                    var paymentRecords = PaymentRecordsBLL.Instance.GetModelList("OrderId=" + orderList[i].Id + " and PayResult=1").FirstOrDefault();
                    dataRow.CreateCell(3).SetCellValue(paymentRecords != null ? paymentRecords.WechatTransactionId : "");//支付流水号
                    dataRow.CreateCell(4).SetCellValue("");//条形码
                    dataRow.CreateCell(8).SetCellValue(orderList[i].PayPrice.ToString());//支付金额
                    dataRow.CreateCell(9).SetCellValue(orderList[i].RandomPayDiscount.ToString());//优惠金额

                    var payWayDes = ((CommonEnum.OrderPayWay)orderList[i].PayWay).GetDescription();
                    var couponResume = OrdersBLL.Instance.GetOrderCouponUseResume(orderList[i].Id).Replace("<br/>", "\r\n");
                    if (orderList[i].PayPrice == 0 && !string.IsNullOrWhiteSpace(couponResume))
                    {
                        payWayDes = "电子水票（券）支付";
                    }
                    dataRow.CreateCell(10).SetCellValue(payWayDes);//支付方式

                    dataRow.CreateCell(11).SetCellValue(orderList[i].ReceiverAddress);//客户地址
                    dataRow.CreateCell(12).SetCellValue(orderList[i].ReceiverName);//客户姓名
                    dataRow.CreateCell(13).SetCellValue(orderList[i].ReceiverPhone);//客户电话
                    dataRow.CreateCell(14).SetCellValue(orderList[i].Remark);//订单备注
                    dataRow.CreateCell(15).SetCellValue(((CommonEnum.OrderStatus)orderList[i].OrderStatus).GetDescription());//订单状态
                    var orderShop = ShopsBLL.Instance.GetModel(orderList[i].ShopId);
                    var orderShopTel = string.Empty;
                    var orderShopName = string.Empty;
                    var orderShopAccount = string.Empty;
                    if (orderShop != null)
                    {
                        orderShopTel = orderShop.Tel;
                        orderShopName = orderShop.Name;
                        var mcAccount = McAccountsBLL.Instance.GetModelList("ShopId=" + orderList[i].ShopId + " and AccountType=1").FirstOrDefault();
                        if (mcAccount != null)
                        {
                            orderShopAccount = mcAccount.UserName;
                        }
                    }
                    dataRow.CreateCell(16).SetCellValue(orderShopTel);//配送店铺电话
                    dataRow.CreateCell(17).SetCellValue(orderShopName);//所属门店
                    dataRow.CreateCell(18).SetCellValue(orderShopAccount);//门店账号
                    var transferShopName = string.Empty;
                    var transferShopAccount = string.Empty;
                    var transferOrder = OrdersBLL.Instance.GetModelList("OrderIdCopiedFrom=" + orderList[i].Id).FirstOrDefault();
                    if (transferOrder != null)
                    {
                        var transferShop = ShopsBLL.Instance.GetModel(transferOrder.ShopId);
                        if (transferShop != null)
                        {
                            transferShopName = transferShop.Name;
                            var transferMcAccount = McAccountsBLL.Instance.GetModelList("ShopId=" + transferOrder.ShopId + " and AccountType=1").FirstOrDefault();
                            if (transferMcAccount != null)
                            {
                                transferShopAccount = transferMcAccount.UserName;
                            }
                        }
                    }
                    dataRow.CreateCell(19).SetCellValue(transferShopName);//转移门店
                    dataRow.CreateCell(20).SetCellValue(transferShopAccount);//转移门店账号
                    dataRow.CreateCell(21).SetCellValue("");//备注1
                    dataRow.CreateCell(22).SetCellValue(couponResume);//订单票券详情
                    var orderDetailList = OrderDetailBLL.Instance.GetModelList("OrderId=" + orderList[i].Id);
                    for (var j = 0; j < orderDetailList.Count; j++)
                    {
                        var strNameExtensionText = string.Empty;
                        var commodityLibInfo =
                                    CommodityLibBLL.Instance.GetCommodityInfoByAppointedShopCommodityIds(
                                        orderDetailList[j].ShopCommodityId.ToString());

                        if (commodityLibInfo != null && commodityLibInfo.Count > 0)
                        {
                            if (commodityLibInfo[0].IsVirtual)
                            {
                                strNameExtensionText += "<font style='color:blue'>【" +
                                                      ((orderList[i].ConsumerOrderType ==
                                                        (int)CommonEnum.ConsumerOrderType.ShopConsumerOrder &&
                                                        commodityLibInfo[0].Id == 87)
                                                          ? "可提现"
                                                          : "不可提现") + "】</font>";
                            }
                        }

                        if (j == 0)
                        {
                            dataRow.CreateCell(5)
                                .SetCellValue(orderDetailList[j].CommodityName + strNameExtensionText +
                                              (orderDetailList[j].IsGift ? "【赠品】" : ""));//购买产品

                            dataRow.CreateCell(6).SetCellValue(orderDetailList[j].Quantity.ToString());//购买数量
                            dataRow.CreateCell(7).SetCellValue(orderDetailList[j].Price.ToString());//产品单价
                        }
                        else
                        {
                            rowIndex++;
                            var detailRow = sheet.CreateRow(rowIndex);
                            detailRow.CreateCell(0).SetCellValue(orderList[i].OrderTime.ToString());//销售日期
                            detailRow.CreateCell(1).SetCellValue(orderList[i].OrderTime.ToString());//订单日期
                            detailRow.CreateCell(2).SetCellValue(orderList[i].OrderNo);//订单号
                            detailRow.CreateCell(3).SetCellValue(paymentRecords != null ? paymentRecords.WechatTransactionId : "");//支付流水号
                            detailRow.CreateCell(4).SetCellValue("");//条形码
                            detailRow.CreateCell(5)
                                .SetCellValue(orderDetailList[j].CommodityName + strNameExtensionText +
                                              (orderDetailList[j].IsGift ? "【赠品】" : ""));//购买产品
                            detailRow.CreateCell(6).SetCellValue(orderDetailList[j].Quantity.ToString());//购买数量
                            detailRow.CreateCell(7).SetCellValue(orderDetailList[j].Price.ToString());//产品单价
                            detailRow.CreateCell(8).SetCellValue(orderList[i].PayPrice.ToString());//支付金额
                            detailRow.CreateCell(9).SetCellValue(orderList[i].RandomPayDiscount.ToString());//优惠金额
                            detailRow.CreateCell(10).SetCellValue(((CommonEnum.OrderPayWay)orderList[i].PayWay).GetDescription());//支付方式
                            detailRow.CreateCell(11).SetCellValue(orderList[i].ReceiverAddress);//客户地址
                            detailRow.CreateCell(12).SetCellValue(orderList[i].ReceiverName);//客户姓名
                            detailRow.CreateCell(13).SetCellValue(orderList[i].ReceiverPhone);//客户电话
                            detailRow.CreateCell(14).SetCellValue(orderList[i].Remark);//订单备注
                            detailRow.CreateCell(15).SetCellValue(((CommonEnum.OrderStatus)orderList[i].OrderStatus).GetDescription());//订单状态
                            detailRow.CreateCell(16).SetCellValue(orderShopTel);//配送店铺电话
                            detailRow.CreateCell(17).SetCellValue(orderShopName);//所属门店
                            detailRow.CreateCell(18).SetCellValue(orderShopAccount);//门店账号
                            detailRow.CreateCell(19).SetCellValue(transferShopName);//转移门店
                            detailRow.CreateCell(20).SetCellValue(transferShopAccount);//转移门店账号
                            detailRow.CreateCell(21).SetCellValue("");//备注1
                            detailRow.CreateCell(22).SetCellValue(couponResume);//订单票券详情
                        }
                    }
                    rowIndex++;
                }

                var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + CommonHelper.GetGuidKey(6) + ".xls";
                var path = System.Web.HttpContext.Current.Server.MapPath("/Files/Order/" + filename);
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/Files/Order/")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/Files/Order/"));
                }
                using (var fs = System.IO.File.Create(path))
                {
                    book.Write(fs);
                }
                #endregion

                result.Status = true;
                result.Message = "/Files/Order/" + filename;
            }
            catch (Exception ex)
            {
                Logger.Error("OrdersController -- ExportOrders" + ex);
                result.Message = "系统未知错误，请联系管理员";
            }
            return Json(result);
        }
    }
}